import logging

from PyQt5 import QtCore
from PyQt5.QtCore import Qt, QEvent, QPoint
from PyQt5.QtGui import QPixmap, QFont, QMouseEvent
from PyQt5.QtWidgets import QFrame, QApplication

from gm.about_software.about_software_ui import Ui_about_software

about_software_css = """
QTextEdit{
   border:none;
}
"""


class AboutSoftware(QFrame):
    def __init__(self):
        super(AboutSoftware, self).__init__()
        self.ui = Ui_about_software()
        self.ui.setupUi(self)
        self.resize(600, 400)  # UI 最小只能设置到602,所以这里重新设置一下
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool)
        self.setStyleSheet(about_software_css)
        self.relative_pos: QPoint = QPoint(0, 0)

    def set_top_title_image(self, img: str):
        self.ui.title_pic_lb.setPixmap(QPixmap(img))

    def set_top_title(self, title: str, font: QFont = None):
        self.ui.title_str_lb.setText(title)
        if font is not None:
            self.ui.title_str_lb.setFont(font)

    def set_about_software_desc(self, desc: str, font: QFont = None):
        self.ui.about_desc_te.setText(desc)
        if font is not None:
            self.ui.about_desc_te.setFont(font)

    def event(self, e: QtCore.QEvent) -> bool:
        try:
            if e.type() == QEvent.ActivationChange:
                logging.info("current event type:" + str(e.type()))
                if QApplication.activeWindow() != self:
                    logging.info("activate window changed, close!")
                    self.close()
            return super().event(e)
        except Exception as e:
            print(e)

    def mousePressEvent(self, event: QMouseEvent) -> None:
        logging.info("mousePressEvent")
        if event.button() == Qt.LeftButton:
            self.relative_pos = self.pos() - event.globalPos()
        elif event.button() == Qt.RightButton:
            self.relative_pos = QPoint(0, 0)
        super().mousePressEvent(event)

    def mouseMoveEvent(self, event: QMouseEvent) -> None:
        logging.info("mouseMoveEvent")
        if self.relative_pos != QPoint(0, 0):
            logging.info(self.relative_pos)
            self.move(event.globalPos() + self.relative_pos)

        super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, a0: QMouseEvent) -> None:
        super().mouseReleaseEvent(a0)
        logging.info("mouseReleaseEvent")
        if a0.button() == Qt.LeftButton:
            self.relative_pos = QPoint(0, 0)


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    test = AboutSoftware()
    test.set_top_title("关于测试")
    test.show()
    sys.exit(app.exec_())
